package logic

import (
	"context"
	"fmt"
	"github.com/friendsofgo/errors"
	"mall/common/cachex"
	"time"

	"github.com/hibiken/asynq"
	"mall/service/mqueue/job/internal/svc"
	// "github.com/pkg/errors"
)

// var ErrCloseOrderFailed = resultx.NewErrCode(resultx.PAYMENT_AUTO_CLOSE_ORDER_FAILED)

// PeriodicityClearIntegralCacheProcessor implements asynq.Handler interface.
type PeriodicityClearIntegralCacheProcessor struct {
	svcCtx *svc.ServiceContext
}

func NewPeriodicityClearIntegralCacheProcessor(svcCtx *svc.ServiceContext) *PeriodicityClearIntegralCacheProcessor {
	return &PeriodicityClearIntegralCacheProcessor{
		svcCtx: svcCtx,
	}
}

// deferred close unpaid order : if return err != nil, asynq will retry
func (l *PeriodicityClearIntegralCacheProcessor) ProcessTask(ctx context.Context, t *asynq.Task) error {
	//今天是周一,清除上周redis缓存
	now := time.Now()
	for i := 1; i <= 7; i++ {
		stockKey := l.getStockKey(now.AddDate(0, 0, -i))
		if count, err := l.svcCtx.BizRedis.DelCtx(ctx, stockKey); err != nil {
			if count == 0 {
				return errors.New("PeriodicityClearIntegralCacheProcessor DelCtx Error: count==0")
			}
			return err
		}
	}
	return nil
}

func (l *PeriodicityClearIntegralCacheProcessor) getStockKey(now time.Time) string {
	// task:remaining:integral:2025-03-14
	return fmt.Sprintf("{%s}:%s", cachex.RemainingIntegral, now.Format("2006-01-02"))
}
